//
//  SAProductVipScreeningView.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/10.
//

#import "SAProductVipScreeningView.h"
#import "SAProductHomeScreeningHeaderView.h"
#import "SAProductHomeScreenCell.h"
#import "SAProductHomeScreeningModel.h"
#import "SAProductGetConditionAPI.h"
#import "SASelectVipsVC.h"
#import "SAProductManufacturerModel.h"
#import "SAVipModel.h"

@interface SAProductVipScreeningView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HTTPAPIDelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSMutableArray  *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,assign) BOOL isOpen;
@property (nonatomic,strong) UIView *backGroundView;
@property (nonatomic,strong) SAProductGetConditionAPI *productGetConditionAPI;
@property (nonatomic,strong) UIView *topView;
@property (nonatomic,strong) UIView *line;
@property (nonatomic,strong) UIImageView *btnImageV;
@property (nonatomic,strong) UITextField *manufacturerTf;
@property (nonatomic,assign) NSString *memberId;
@property (nonatomic,strong) NSString *memberName;
@property (nonatomic,strong) UIView *hiddenView;
@property (nonatomic,assign) float height;//适配高度
@property (nonatomic,strong) UIButton *delBtn;

@end

@implementation SAProductVipScreeningView

+(instancetype)shareCornView {
    SAProductVipScreeningView * shareView = [[SAProductVipScreeningView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

+(instancetype)shareCornView2 {
    SAProductVipScreeningView * shareView = [[SAProductVipScreeningView alloc] initWithFrame2:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        [self creatUI];
    }
    return self;
}

//适配高度
-(instancetype)initWithFrame2:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        self.height = 49;
        [self creatUI];
    }
    return self;
}

-(void)setDelegate:(id)delegate {
    _delegate = delegate;
    self.hiddenView.hidden = YES;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.dataArray removeAllObjects];
    for ( NSDictionary *dict in (NSArray *)data[@"data"]) {
        SAProductHomeScreeningModel *model = [SAProductHomeScreeningModel mj_objectWithKeyValues:dict];
        [self.dataArray addObject:model];
    }
    [self clearData];
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    self.manufacturerTf.text = @"";
    self.memberId = @"";
    self.memberName = @"";
    return YES;
}

-(void)creatUI {
    
    self.memberId = 0;
    self.memberName = @"";
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(60), 0, kScaleNum(315), kScreenHeight)];
    backGroundView.backgroundColor = [UIColor whiteColor];
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    self.backGroundView = backGroundView;
    
    [backGroundView addSubview:self.topView];
    [backGroundView addSubview:self.line];
    //    [backGroundView addSubview:self.btnImageV];
        
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(kScaleNum(0), kScreenHeight - kScaleNum(SafeFooterHeight + 45 + self.height), kScaleNum(157.5), kScaleNum(45 + SafeFooterHeight));
        [deleteBtn addTarget:self action:@selector(clearData) forControlEvents:UIControlEventTouchUpInside];
        [deleteBtn setTitle:@"清除" forState:UIControlStateNormal];
        deleteBtn.backgroundColor = kColor(196, 196, 196, 1);
        [deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [backGroundView addSubview:deleteBtn];

        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        confirmBtn.frame = CGRectMake(kScaleNum(157.5), kScreenHeight - kScaleNum(SafeFooterHeight + 45 + self.height), kScaleNum(157.5), kScaleNum(45 + SafeFooterHeight));
        [confirmBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
        [confirmBtn setTitle:@"查询" forState:UIControlStateNormal];
        confirmBtn.backgroundColor = kPinkColor;
        [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [backGroundView addSubview:confirmBtn];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(kScaleNum(68), kScaleNum(25));
    flow.minimumInteritemSpacing = kScaleNum(11);
    //设置每行之间的最小间隔
    flow.minimumLineSpacing = kScaleNum(10);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(15), kScaleNum(StatusHeight + 15), kScaleNum(285), kScreenHeight - kScaleNum(StatusHeight + 75 + SafeFooterHeight + self.height)) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource=self;
    _collectionView.delegate=self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [backGroundView addSubview:_collectionView];
    [_collectionView registerClass:[SAProductHomeScreenCell class] forCellWithReuseIdentifier:@"SAProductHomeScreenCell"] ;
    [_collectionView registerClass:[SAProductHomeScreeningHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductHomeScreeningHeaderView"];
    
    [backGroundView addSubview:self.hiddenView];
}

-(void)loadData:(NSMutableArray *)array MemberName:(NSString *)memberName MemberId:(NSString *)memberId; {
    if (array.count == 0) {
        self.memberId = @"";
        self.memberName = @"";
        [self loadData];
    }else {
        self.memberId = memberId;
        self.memberName = memberName;
        if (self.memberName.length > 0) {
            self.manufacturerTf.text = self.memberName;
            self.delBtn.hidden = NO;
        }else {
            self.delBtn.hidden = YES;
        }
        
        for (SAProductHomeScreeningModel *model in array) {
            SAProductHomeScreeningModel *newModel = [SAProductHomeScreeningModel new];
            newModel.name = model.name;
            newModel.isOpen = model.isOpen;
            NSMutableArray <SAProductHomeScreeningList *>*voList = [NSMutableArray array];
            for (SAProductHomeScreeningList *list in model.voList) {
                SAProductHomeScreeningList *newList = [SAProductHomeScreeningList new];
                newList.attrId = list.attrId;
                newList.attrName = list.attrName;
                newList.check = list.check;
                newList.conditionId = list.conditionId;
                newList.conditionName = list.conditionName;
                [voList addObject:newList];
            }
            newModel.voList = voList;
            [self.dataArray addObject:newModel];
        }
    }
}

-(void)loadData {
    [self.productGetConditionAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SAProductHomeScreeningModel *model = self.dataArray[section];
    if (model.voList.count > 6) {
        if (model.isOpen == YES) {
            return model.voList.count;
        }else {
            return 6;
        }
    }else {
        return model.voList.count;
    }
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"SAProductHomeScreenCell";
    SAProductHomeScreenCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    SAProductHomeScreeningModel *model = self.dataArray[indexPath.section];
    SAProductHomeScreeningList *list = model.voList[indexPath.row];
//    if (self.isFirst == YES) {
//        if (indexPath.row == 0) {
//            list.check = YES;
//        }
//    }
    [cell loadDat:list];
    
    return cell;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SAProductHomeScreeningModel *model = self.dataArray[indexPath.section];
    for (SAProductHomeScreeningList *list in model.voList) {
        list.check = NO;
    }
    SAProductHomeScreeningList *list = model.voList[indexPath.row];
    list.check = YES;
    [self.collectionView reloadData];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    //返回段头段尾视图
    __weak typeof(self) weakSelf = self;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SAProductHomeScreeningHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductHomeScreeningHeaderView" forIndexPath:indexPath];
        SAProductHomeScreeningModel *model = self.dataArray[indexPath.section];
        headerView.anScreenBlock = ^(BOOL isOpen) {
            model.isOpen = isOpen;
            [weakSelf.collectionView reloadData];
        };
        [headerView loadData:model];
        return headerView;
    }
    //如果底部视图
    if (kind == UICollectionElementKindSectionFooter)
    {
        
        
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return  CGSizeMake(kScaleNum(315), kScaleNum(52));;
}

#pragma mark--UICollectionViewDelegateFlowLayout的协议方法

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(kScaleNum(0), kScaleNum(0),kScaleNum(15),kScaleNum(0));
}


-(void)clickedArrowBtn {
    __weak typeof(self) weakSelf = self;
    SASelectVipsVC *pushVC = [SASelectVipsVC new];
    pushVC.selectBlock = ^(SAVipModel *model) {
        weakSelf.manufacturerTf.text = model.memberName;
        weakSelf.memberId = model.memberId;
        weakSelf.memberName = model.memberName;
        weakSelf.delBtn.hidden = NO;
    };
    [[self.delegate navigationController] pushViewController:pushVC animated:YES];
}

-(void)clickedDelBtn {
    self.manufacturerTf.text = @"";
    self.memberId = @"";
    self.memberName = @"";
    self.delBtn.hidden = YES;
}

#pragma mark -- lazy
-(NSMutableArray *)dataArray {
    if(_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)showView:(UIViewController *)Sview {
    if(Sview==nil){
        [[[UIApplication sharedApplication].windows lastObject] addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent {
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)clearData {
    self.manufacturerTf.text = @"";
    self.memberId = @"";
    self.memberName = @"";
    for (SAProductHomeScreeningModel *model in self.dataArray) {
        for (SAProductHomeScreeningList *list in model.voList) {
            list.check = NO;
        }
        if ([model.name isEqualToString:@"状态"]) {
            if (model.voList.count > 1 && [model.voList[1].attrName isEqualToString:@"已上架"]) {
                model.voList[1].check = YES;
            }else if (model.voList.count > 0){
                model.voList[0].check = YES;
            }
        }else if ([model.name isEqualToString:@"排序"]) {
            if (model.voList.count > 10 && [model.voList[10].attrName isEqualToString:@"近期未拿货"]) {
                model.voList[10].check = YES;
            }else if (model.voList.count > 0){
                model.voList[0].check = YES;
            }
        }else {
            if (model.voList.count > 0) {
                model.voList[0].check = YES;
            }
        }
    }

    [self.collectionView reloadData];
}

-(void)confirmationTapEvent {
    if (self.screeningBlock) {
        self.screeningBlock(self.dataArray,self.memberName, self.memberId);
    }
    [self shareDissTapEvent];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    CGPoint point = [[touches anyObject] locationInView:self];
    point = [self.backGroundView.layer convertPoint:point fromLayer:self.layer];
    if (![self.backGroundView.layer containsPoint:point]) {
        [UIView animateWithDuration:0.5f animations:^{
            
            self.alpha = 0.0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
}

-(SAProductGetConditionAPI *)productGetConditionAPI {
    if (!_productGetConditionAPI) {
        _productGetConditionAPI = [SAProductGetConditionAPI apiWithDelegate:self];
    }
    return _productGetConditionAPI;
}

-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight - 44), kScaleNum(315), kScaleNum(44))];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(15, 0, 100, 44)];
        titleLab.text = @"会员";
        titleLab.textAlignment = NSTextAlignmentLeft;
        titleLab.font = kFont(14);
        titleLab.textColor = kColor(51, 51, 51, 1);
        [_topView addSubview:titleLab];
        
        UITextField *manufacturerTf = [[UITextField alloc] initWithFrame:SARectMake(125, 0, 140, 44)];
        manufacturerTf.font = kFont(14);
        manufacturerTf.textColor = kGrayColor;
        manufacturerTf.textAlignment = NSTextAlignmentRight;
        manufacturerTf.clearButtonMode = UITextFieldViewModeUnlessEditing;
        manufacturerTf.delegate = self;
        manufacturerTf.userInteractionEnabled = NO;
        self.manufacturerTf = manufacturerTf;
        [_topView addSubview:manufacturerTf];
        
        UIButton *arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        arrowBtn.frame = SARectMake(0, 0, 315, 44);
        arrowBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        arrowBtn.imageEdgeInsets = kEdgeInsetsMake(0, 0, 0, 15);
        [arrowBtn setImage:[UIImage imageNamed:@"shop_rightAllow"] forState:UIControlStateNormal];
        [arrowBtn addTarget:self action:@selector(clickedArrowBtn) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:arrowBtn];
        
        UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        delBtn.frame = SARectMake(230, 0, 40, 44);
        [delBtn addTarget:self action:@selector(clickedDelBtn) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:delBtn];
        delBtn.hidden = YES;
        self.delBtn = delBtn;
    }
    return _topView;
}

-(UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScaleNum(8))];
        _line.backgroundColor = kLineColor;
    }
    return _line;
}

-(UIImageView *)btnImageV {
    if (!_btnImageV) {
        _btnImageV = [[UIImageView alloc] initWithFrame:CGRectMake(kScaleNum(135), kScreenHeight - kScaleNum(SafeFooterHeight + 50 + self.height), kScaleNum(157), kScaleNum(37))];
        _btnImageV.image = [UIImage imageNamed:@"shop_btn2"];
    }
    return _btnImageV;
}

-(UIView *)hiddenView {
    if (!_hiddenView) {
        _hiddenView = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(0), 0, kScaleNum(315), kScaleNum(StatusHeight + 15))];
        _hiddenView.backgroundColor = [UIColor whiteColor];
        _hiddenView.hidden = NO;
    }
    return _hiddenView;
}

@end
